﻿using _111.QywxDocument.SafeRecord;
using guidHelper;
using MyDapperApi.Models;
using MyDapperApi.Services.QywxBase;
using Newtonsoft.Json;
using QYWXUpdate.DataModel;
using QYWXUpdate.DataModel.QYWXDocument;
using static MyDapperApi.Services.DateBaseService;

namespace MyDapperApi.Services.QywxDocument.SafeRecord;
public class DocSafeRecordService : IDocSafeRecordService
{
    private readonly IConfiguration _configuration;
    private readonly IHttpClientFactory _httpClientFactory;
    private readonly IDateBaseService _dateBaseService;
    private readonly IQywxBaseService _qywxBaseService;
    public readonly ICsvService _csvService;
    private readonly string _qywxReceiveToken = "sdas";
    private readonly string _corpId;

    // 通过依赖注入获取配置，从而读取连接字符串
    public DocSafeRecordService(IHttpClientFactory httpClientFactory, IConfiguration configuration, IDateBaseService dateBaseService, ICsvService csvService,
        IQywxBaseService qywxBaseService)
    {
        _configuration = configuration;
        _httpClientFactory = httpClientFactory;
        _dateBaseService = dateBaseService;
        _csvService = csvService;
        _corpId = configuration["QywxSettings:CorpId"];
        _qywxBaseService = qywxBaseService;
    }

    /// <summary>
    /// 企业微信推送自定义功能标准方法...
    /// </summary>
    /// <param name="request"></param>
    /// <returns></returns>
    public async Task<CommonResponse> UpdateSaveRecordDocument(string SheetId, string RecordId)
    {
        var result = new CommonResponse();
        var token = await _qywxBaseService.GetAccessTokenAsync("ww41ce2a97523f4d1a", "xKW0MRSs9azutLLPJt2hDi6gtpYDpdeas5azgxcbUnQ");
        var client = _httpClientFactory.CreateClient();

        var content1 = new
        {
            docid = "dcE-wSUE1WnAQ4vtPfjfZwu-a93Zw-Pr8HsigbTsNQ7zE33r-vV5R5ijVHSIaDm3Vs3nsHaPOnk4pNz2_PRcaPgQ",
            sheet_id = SheetId,
            record_ids = new List<string>() { RecordId },
        };
        var temp = JsonConvert.SerializeObject(content1);

        var content = new StringContent(
            JsonConvert.SerializeObject(content1),
            System.Text.Encoding.UTF8,
            "application/json");

        var response = new HttpResponseMessage();


        response = await client.PostAsync(
        $"https://qyapi.weixin.qq.com/cgi-bin/wedoc/smartsheet/get_records?access_token={token}",
        content);

        if (response.IsSuccessStatusCode)
        {
            var responseStream = await response.Content.ReadAsStreamAsync();

            using (responseStream)
            {
                var res = await _qywxBaseService.StreamToStringAsync(responseStream);
                var wxRespon = JsonConvert.DeserializeObject<CommonGetDocDetailResponse<SaveRecordDetail>>(res);

                var CsvList = new List<DocumentSafeRecordEntity>();

                foreach (var item in wxRespon.records)
                {
                    var tempItem = new DocumentSafeRecordEntity()
                    {
                        Id = ToolHelper.GUIDTO16(),
                        Is_Deleted = 0,
                        Created_On = DateTime.Now,
                        Modified_On = DateTime.Now,
                        RecordId = item.record_id,
                        CreateTime = ToolHelper.ConvertMillisecondsToDateTimeString(long.Parse(item.create_time)).ToString("yyyy-MM-dd HH:mm:ss") ?? string.Empty,
                        Filler = item.values.填写人[0].user_id ?? string.Empty,
                        FillTime = ToolHelper.ConvertMillisecondsToDateTimeString(long.Parse(item.values.填写时间)).ToString("yyyy-MM-dd HH:mm:ss") ?? string.Empty,
                        IsLongLight = ChangeTextToInt(item.values.巡房状态房间有长明灯[0].text),
                        IsLocked = ChangeTextToInt(item.values.巡房状态房间未上锁[0].text),
                        IsArranged = ChangeTextToInt(item.values.巡房状态房间物品摆放整齐[0].text),
                        IsSeenTechnicians = ChangeTextToInt(item.values.巡房状态房间看得见客户或技师[0].text),
                        IsPatrolStatus = ChangeTextToInt(item.values.巡房状态技术老师按照标准服务流程服务[0].text),
                        RoomNumber = item.values.房间号[0].text ?? string.Empty,
                        Department = item.values.所在部门[0].text ?? string.Empty,
                        TechnicianNumber = item.values.技师号[0].text ?? string.Empty,
                        MassageArea = item.values.技师按摩部位[0].text ?? string.Empty,
                        ServerItem = item.values.服务项目[0].text ?? string.Empty,
                        UserType = item.values.用户类型[0].text ?? string.Empty,
                        Shop = item.values.门店[0].text ?? string.Empty,
                    };
                    //CsvList.Add(tempItem);

                    result = await CheckSafeRecordDocument(tempItem);
                }

                //result = await _csvService.AppendToCsv("D:\\File\\data.csv",CsvList,new GetSafeRecordDocumentCsvMep());


                if (wxRespon.has_more)
                {
                    result = await GetDocument(wxRespon.next, 200);
                }

                result.SetSuccess(wxRespon);

                return result;
            }

        }
        result.SetError("与微信服务器交互失败");
        response.EnsureSuccessStatusCode();
        return result;
    }

    /// <summary>
    /// 企业微信推送自定义功能标准方法...
    /// </summary>
    /// <param name="request"></param>
    /// <returns></returns>
    public async Task<CommonResponse> GetDocument(int offset = 0, int limit = 200)
    {
        var result = new CommonResponse();
        var token = await _qywxBaseService.GetAccessTokenAsync("ww41ce2a97523f4d1a", "xKW0MRSs9azutLLPJt2hDi6gtpYDpdeas5azgxcbUnQ");
        var client = _httpClientFactory.CreateClient();

        var content1 = new
        {
            docid = "dcE-wSUE1WnAQ4vtPfjfZwu-a93Zw-Pr8HsigbTsNQ7zE33r-vV5R5ijVHSIaDm3Vs3nsHaPOnk4pNz2_PRcaPgQ",
            sheet_id = "tlL1QJ",
            offset = offset,
            limit = limit
        };
        var temp = JsonConvert.SerializeObject(content1);

        var content = new StringContent(
            JsonConvert.SerializeObject(content1),
            System.Text.Encoding.UTF8,
            "application/json");

        var response = new HttpResponseMessage();


        response = await client.PostAsync(
        $"https://qyapi.weixin.qq.com/cgi-bin/wedoc/smartsheet/get_records?access_token={token}",
        content);

        if (response.IsSuccessStatusCode)
        {
            var responseStream = await response.Content.ReadAsStreamAsync();

            using (responseStream)
            {
                var res = await _qywxBaseService.StreamToStringAsync(responseStream);
                var wxRespon = JsonConvert.DeserializeObject<CommonGetDocDetailResponse<SaveRecordDetail>>(res);

                var CsvList = new List<DocumentSafeRecordEntity>();

                foreach (var item in wxRespon.records)
                {
                    var tempItem = new DocumentSafeRecordEntity()
                    {
                        Id = ToolHelper.GUIDTO16(),
                        Is_Deleted = 0,
                        Created_On = DateTime.Now,
                        Modified_On = DateTime.Now,
                        RecordId = item.record_id,
                        CreateTime = ToolHelper.ConvertMillisecondsToDateTimeString(long.Parse(item.create_time)).ToString("yyyy-MM-dd HH:mm:ss") ?? string.Empty,
                        Filler = item.values.填写人[0].user_id ?? string.Empty,
                        FillTime = ToolHelper.ConvertMillisecondsToDateTimeString(long.Parse(item.values.填写时间)).ToString("yyyy-MM-dd HH:mm:ss") ?? string.Empty,
                        IsLongLight = ChangeTextToInt(item.values.巡房状态房间有长明灯[0].text),
                        IsLocked = ChangeTextToInt(item.values.巡房状态房间未上锁[0].text),
                        IsArranged = ChangeTextToInt(item.values.巡房状态房间物品摆放整齐[0].text),
                        IsSeenTechnicians = ChangeTextToInt(item.values.巡房状态房间看得见客户或技师[0].text),
                        IsPatrolStatus = ChangeTextToInt(item.values.巡房状态技术老师按照标准服务流程服务[0].text),
                        RoomNumber = item.values.房间号[0].text ?? string.Empty,
                        Department = item.values.所在部门[0].text ?? string.Empty,
                        TechnicianNumber = item.values.技师号[0].text ?? string.Empty,
                        MassageArea = item.values.技师按摩部位[0].text ?? string.Empty,
                        ServerItem = item.values.服务项目[0].text ?? string.Empty,
                        UserType = item.values.用户类型[0].text ?? string.Empty,
                        Shop = item.values.门店[0].text ?? string.Empty,
                    };
                    //CsvList.Add(tempItem);

                    result = await CheckSafeRecordDocument(tempItem);
                }

                //result = await _csvService.AppendToCsv("D:\\File\\data.csv",CsvList,new GetSafeRecordDocumentCsvMep());


                if (wxRespon.has_more)
                {
                    result = await GetDocument(wxRespon.next, 200);
                }

                result.SetSuccess(wxRespon);

                return result;
            }

        }
        result.SetError("与微信服务器交互失败");
        response.EnsureSuccessStatusCode();
        return result;
    }

    public int ChangeTextToInt(string item = "")
    {
        // 先处理null的情况，将null转换为空字符串
        if (item == null)
        {
            return 3;//空值
        }

        if (item == "是")
        {
            return 1;
        }
        else
        {
            return 0;
        }
    }

    public async Task<CommonResponse> CheckSafeRecordDocument(DocumentSafeRecordEntity request)
    {
        var result = new CommonResponse();

        //var entity = new DocumentSafeRecordEntity();

        var sqlbuilder = new SqlBuilder();
        var sql = "SELECT * FROM document_safe_record WHERE 1 = 1 AND is_deleted = 0 ";
        sqlbuilder.Add(" AND record_id = @RecordId ", "@RecordId", request.RecordId);

        var entity = await _dateBaseService.QueryFirstOrDefaultAsync<DocumentSafeRecordEntity>(sql, sqlbuilder);

        if (entity != null)
        {
            result = await SaveSafeRecordDocument(entity, 1);
        }
        else
        {
            result = await SaveSafeRecordDocument(request, 0);
        }

        return result;
    }

    public async Task<CommonResponse> SaveSafeRecordDocument(DocumentSafeRecordEntity request, int type)//0新增，1修改
    {
        var result = new CommonResponse();
        var sql = string.Empty;
        var sqlbuilder = new SqlBuilder();
        sqlbuilder.Add("", "@Id", request.Id);
        sqlbuilder.Add("", "@IsDeleted", request.Is_Deleted);
        sqlbuilder.Add("", "@RecordId", request.RecordId);
        sqlbuilder.Add("", "@CreateTime", request.CreateTime);
        sqlbuilder.Add("", "@Filler", request.Filler);
        sqlbuilder.Add("", "@FillTime", request.FillTime);
        sqlbuilder.Add("", "@IsLongLight", request.IsLongLight);
        sqlbuilder.Add("", "@IsLocked", request.IsLocked);
        sqlbuilder.Add("", "@IsArranged", request.IsArranged);
        sqlbuilder.Add("", "@IsSeenTechnicians", request.IsSeenTechnicians);
        sqlbuilder.Add("", "@IsPatrolStatus", request.IsPatrolStatus);
        sqlbuilder.Add("", "@RoomNumber", request.RoomNumber);
        sqlbuilder.Add("", "@Department", request.Department);
        sqlbuilder.Add("", "@TechnicianNumber", request.TechnicianNumber);
        sqlbuilder.Add("", "@MassageArea", request.MassageArea);
        sqlbuilder.Add("", "@ServerItem", request.ServerItem);
        sqlbuilder.Add("", "@UserType", request.UserType);
        sqlbuilder.Add("", "@Shop", request.Shop);

        if (type == 0)
        {
            sql = @$"INSERT INTO document_safe_record (
    id, 
    created_on, 
    is_deleted, 
    record_id, 
    create_time, 
    filler, 
    filltime, 
    is_long_light, 
    is_locked, 
    is_arranged, 
    is_seen_technicians, 
    is_patrol_status, 
    room_number, 
    department,
    technician_number, 
    massage_area, 
    server_item, 
    user_type, 
    shop
) VALUES (
    @Id, 
    @CreatedOn, 
    @IsDeleted, 
    @RecordId, 
    @CreateTime, 
    @Filler, 
    @FillTime, 
    @IsLongLight, 
    @IsLocked, 
    @IsArranged, 
    @IsSeenTechnicians, 
    @IsPatrolStatus, 
    @RoomNumber, 
    @Department,
    @TechnicianNumber, 
    @MassageArea, 
    @ServerItem, 
    @UserType, 
    @Shop
);";
            sqlbuilder.Add("", "@CreatedOn", request.Created_On);
        }
        else
        {
            sql = $@"UPDATE document_safe_record 
SET 
    modified_on = @ModifiedOn,
    is_deleted = @IsDeleted,
    record_id = @RecordId,
    create_time = @CreateTime,
    filler = @Filler,
    filltime = @FillTime,
    is_long_light = @IsLongLight,
    is_locked = @IsLocked,
    is_arranged = @IsArranged,
    is_seen_technicians = @IsSeenTechnicians,
    is_patrol_status = @IsPatrolStatus,
    room_number = @RoomNumber,
    department = @Department,
    technician_number = @TechnicianNumber,
    massage_area = @MassageArea,
    server_item = @ServerItem,
    user_type = @UserType,
    shop = @Shop
WHERE id = @Id;";
            sqlbuilder.Add("", "@ModifiedOn", request.Modified_On);
        }

        result = await _dateBaseService.ExecuteAsync(sql, sqlbuilder);
        return result;
    }

    /// <summary>
    /// 删除文档数据
    /// </summary>
    /// <param name="RecordId"></param>
    /// <returns></returns>
    public async Task<CommonResponse> DeleteSafeRecordDocument(string RecordId)
    {
        var result = new CommonResponse();

        var sql = string.Empty;
        var sqlbuilder = new SqlBuilder();
        sql = $@"UPDATE document_safe_record 
SET 
    modified_on = @ModifiedOn,
    is_deleted = 1
WHERE id = @Id;";
        sqlbuilder.Add("", "@Id", RecordId);
        sqlbuilder.Add("", "@ModifiedOn", DateTime.Now);
        result = await _dateBaseService.ExecuteAsync(sql, sqlbuilder);
        return result;
    }
}